﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings;
using System.Web;
using Liber;
using Liber.WEB;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FlashQ.Main
{
    public class FlashQController : LiberController
    {
        public ActionResult Index()
        {
            return PhysicalFile(MapPath("/index.html"), "text/html");
        }

        /// <summary>
        /// 创建一个长期有效的客户端标识
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult NewSession()
        {
            return Json(FnResult.Sucess(SessionID));
        }

        [HttpPost]
        public JsonResult Login()
        {
            string key = Request.TryGet("key", "");
            string pwd = Request.TryGet("pwd", "");

            /*前端将密码转换为16进制数字，后端进行转换并去除第一个字母_*/
            
            /*通过绑定的扩展帐号登录时传递open参数*/
            string opensrc = Request.TryGet("open", "");

            /*动态验证码登录时使用*/
            string captcha = Request.TryGet("captcha", "");

            FnResult<DyObject> r = null;
            if (!captcha.IsNull())
            {
                /*通过动态验证码登录时*/
                var vc = Cache.Get("SMSCaptcha", "CaptchaLogin" + key);
                if (XMLSetting.DefaultSetting.First("SMS").First("Enable").Value.TryBool(false) == true && (captcha.IsNull() || vc == null || vc.ToString() != captcha)) {
                    return Json(FnResult.Failure("AcntController", "ErrCaptcha"));
                }

                r = API.NoauthorRequest("MineApp@FindAcnt")
                       .Set("mphone", key)
                       .WaitResult();
                if (!r.IsPositive)
                {
                    //PC端使用标准登录逻辑，不自动创建帐号
                    return Json(r);
                }
            }
            else
            {
                r = API.NoauthorRequest("FlashQBase@CheckIn")
                       .Set("key", key)
                       .Set("password", pwd.UnMD4())
                       .Set("opensrc", opensrc)
                       .WaitResult();
            }

            if (r.IsPositive)
            {
                SetLoginStatus(r.Data, true);
            }
            return Json(r);
        }

        /// <summary>
        /// 通过发送短信验证码验证手机号码的合法性
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ValidatePhone(string mphone, string scene, string token)
        {
            if (mphone.IsNull() || scene.IsNull() || token.IsNull())
            {
                return Json(FnResult<DyObject>.Failure("System", "RequiredArgs").SetError("Args", "mphone"));
            }

            if (token != mphone.MD5Encrypt_normal().Replace("-", "").ToLower())
            {
                return Json(FnResult.Failure("System", "AccessDenied"));
            }

            //全局开关检查
            bool IsSMSEnable = XMLSetting.DefaultSetting.First("SMS").First("Enable").Value.TryBool(false);
            if (!IsSMSEnable)
            {
                return Json(FnResult.Sucess());
            }

            //限流控制[例如腾讯云，已经提供了一些限流规则，就没必要在我们这边实现]
            bool limiting = XMLSetting.DefaultSetting.First("SMS").First("Limiting").Value.TryBool(true);

            //单个会话发送间隔控制，不能少于60秒
            int tag = Cache.GetStr("SMSInterval", UID.ToString()).TryInt(0);
            if (tag > 0)
            {
                Log("SMSShortInterval", "", LogType.Warning);
                return Json(FnResult<DyObject>.Failure("System", "SMSShortInterval"));
            }
            else
            {
                Cache.Set("SMSInterval", UID.ToString(), "100", 1);
            }

            if (limiting)
            {
                //单个手机号码累计控制，1小时内不能超过10次
                int tag2 = Cache.GetStr("SMSMaxTimes", mphone).TryInt(0);
                if (tag2 > 10)
                {
                    Log("SMSMaxTimes", "", LogType.Warning);
                    return Json(FnResult<DyObject>.Failure("System", "SMSMaxTimes"));
                }
                else
                {
                    Cache.Set("SMSMaxTimes", mphone, (tag2 + 1).ToString(), 60);
                }
            }

            //检查已缓存的验证码
            string code= Cache.GetStr("SMSCaptcha", scene + mphone);
            if (code.IsNull()) {
                code = new Random(DateTime.Now.Millisecond).Next(100000, 900000).ToString();
            }

            Cache.Set("SMSCaptcha", scene + mphone, code, 5);

            SMS.Send(scene, new string[] { code }, mphone);
            return Json(FnResult.Sucess());
        }

        [HttpPost]
        public JsonResult SetPassword(string pwd)
        {
            var r= API.Request(UID,UNAME,"DemoApp@SetPassword")
                   .Set("password", pwd)
                   .WaitResult();

            return Json(r);
        }


        /// <summary>
        /// 钱包充值
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult RechargeWallet()
        //{
        //    decimal amount = Request.TryGetDecimal("amount", 0M);
        //    string way = Request.TryGet("way", ""); //支付方式
        //    string os = Request.TryGet("os", "");   //手机系统类型
        //    long walletId = Request.TryGetLong("walletid", -1);  //充值目标钱包ID

        //    var rtn = API.Request(UID, UNAME, "DemoApp@NewPay")
        //                 .Set("payfor","Wallet")
        //                 .Set("toobj", walletId)
        //                 .Set("amount", amount)
        //                 .Set("paychannel", "FZF-"+way)
        //                 .WaitResult();

        //    if (rtn.IsPositive)
        //    {
        //        long payId = (long)rtn.Data["id"];
        //        rtn.Data.Set("app_clientid", SessionID);

        //        Cache.Set<DyObject>("OnPaying", payId.ToString(), rtn.Data,5);
        //        string toPayApp = FzfPay.Pay(os == "A" ? "ANDROID" : "IOS", way, payId, amount, "闪Q空间-钱包充值");
        //        if (toPayApp.IsNull())
        //        {
        //            return Json(FnResult<DyObject>.Failure("System", "PayChannelFail"));
        //        }
        //        else
        //        {
        //            rtn.Data.Set("PayData", toPayApp);
        //            return Json(rtn);
        //        }
        //    }
        //    return Json(rtn);
        //}


        public static void PayEnd(long payBillId, string outPayId, decimal payAmount, DateTime payEndTime)
        {
            var pb = Cache.Get<DyObject>("OnPaying", payBillId.ToString());
            if (pb != null)
            {
                Cache.Remove("OnPaying", payBillId.ToString());

                //更新支付单状态
                API.NoauthorTask("DemoApp@PayEnd")
                   .Set("payid", payBillId)
                   .Set("openid", outPayId)
                   .Set("receive", payAmount)
                   .Set("paytime", payEndTime)
                   .Set("payfor", pb["payfor"].ToString())
                   .Set("payobj", pb["objid"].TryLong(-1))
                   .End();

                if (pb["app_clientid"] != null)
                {
                    //给客户端发送消息
                    switch (pb["payfor"].ToString())
                    {
                        case "Wallet":
                            var msg = FnResult<DyObject>.Sucess(new DyObject().Set("BizType", "WalletRecharged")
                                                    .Set("WalletIdStr",pb["objid"].ToString())
                                                    .Set("Amount", payAmount));
                            IM.SendMsg(pb["app_clientid"].TryInt(-1), msg.FastJson());
                            break;
                        case "Order":
                            var msg2 = FnResult<DyObject>.Sucess(new DyObject().Set("BizType", "OrderPayed")
                                                         .Set("OrderIdStr",pb["objid"].ToString())
                                                         .Set("Amount", payAmount));
                            IM.SendMsg(pb["app_clientid"].TryInt(-1), msg2.FastJson());
                            break;
                    }

                }
            }
        }

        /// <summary>
        /// 执行已支付订单的后继操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DoOrder()
        {
            string rq = Request.TryGet("operation", "");
            long ordid = Request.TryGetLong("orderid", -1);

            return Json(null);
        }

        /// <summary>
        /// 查询当前用户近期订单
        /// </summary>
        /// <returns></returns>
        public JsonResult MyOrders()
        {
            var r = API.Request(UID, UNAME, "DemoApp@QueryOrders")
                       .WaitResult();

            return Json(r);
        }


        /// <summary>
        /// 获取用户钱包信息
        /// </summary>
        /// <returns></returns>
        public JsonResult MyWallet()
        {
            var rtn = API.Request(UID, UNAME, "DemoApp@GetMyAsset")
                         .Set("kind", "Wallet")
                         .WaitResult();
            if (rtn.IsPositive)
            {
                List<DyObject> asts = rtn.Data["Assets"] as List<DyObject>;
                rtn.Data.Set("balance", asts[0]["balance"]);
            }
            return Json(rtn);
        }
    }

    /// <summary>
    /// 富之富支付控制器
    /// </summary>
    //public class FzfPay:LiberController
    //{
    //    static readonly string openid = "17120000573495";
    //    static readonly string fq_pvtKey_net = "<RSAKeyValue><Modulus>w/PfGtvyYXoIsvIFFwZzevz8H0L/nthShPoQH5zau4WTIq34wx7kvvVAlULkBUt0luJ7PmyNYtqRGNl5Xeg4069ohgf3eHw1V0lNe/Vuq8wixYCbLEZO+TAMGL/VEzgFWofZiW78sfISCyE48cV+S8qj3jGZCU+mjyXBhEzF5+U=</Modulus><Exponent>AQAB</Exponent><P>+KZorPNnDGfB3Aj9PkhH6N32DN4WDwcZw2cdmUXAeSDXd9G1WIZfQZhjPCUdfdlYWfnepYGFqNqiAVTdu1ULiw==</P><Q>yb6wenzKPDa4IM30wkvrtUMVAraMH1LvCvu6kBSQ3CoUgwbrAYT0yYMAafoypEVgpW5JzumWer6Cf3LvEOEITw==</Q><DP>okGFIQccgZ3bhUhgaRolwrHE9BSgdGH/z+EkEXbQ6LojoM659fCJjHZymzblDdCctOo2/e2NWOiCuze0EaCnjQ==</DP><DQ>UE0spbSiMtF8/OG9uNDLY3zuEgRjRdyW9YI5QjxNZLUDMRxB0nr/jG4ubgB+w9Axped+TXPAx96oxt4Stl88FQ==</DQ><InverseQ>AzNGcVaIW47xocL6wm/ro4/ERTtldQZfpA6OiocOMsNmiakTVyD5qXeK9MyUPsQwojf1uyN0s4s1G+7Zd4z02w==</InverseQ><D>fv+QqozAk5KPDsMyr1CcCarrEKvQljeni82yI3r6fKy+xqwwXO2p3WWAXPzEYfYccyoILFYYcGgtwAg607UNFmlhXfBLXMc/0N+cuB68dUWEEzzruxZ5xk3VbynYF88Fe17hpy7OnEhztepfm1YSPEaBxXD90ghKDcMsoVSuYwU=</D></RSAKeyValue>";
    //    static readonly string fzf_pubKey_net = "<RSAKeyValue><Modulus>1c176jTrVPj0Ox5pLoLBwTSk1I+SJOfZG9mAB+JSVjYMsQNRH939zdEhv6uaJRR/iXbc3Pw8fD6NWJWC00GvMcSX0Iau97ftbCvbYFgoewjmcHResDs898kUtR+yoiVy+2CCp24J8JNs0I7OipQm6ya6njffbDcXLvR7sobh8yE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
    //    static readonly string fq_pvtKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPz3xrb8mF6CLLyBRcGc3r8/B9C/57YUoT6EB+c2ruFkyKt+MMe5L71QJVC5AVLdJbiez5sjWLakRjZeV3oONOvaIYH93h8NVdJTXv1bqvMIsWAmyxGTvkwDBi/1RM4BVqH2Ylu/LHyEgshOPHFfkvKo94xmQlPpo8lwYRMxeflAgMBAAECgYB+/5CqjMCTko8OwzKvUJwJqusQq9CWN6eLzbIjevp8rL7GrDBc7andZYBc/MRh9hxzKggsVhhwaC3ACDrTtQ0WaWFd8Etcxz/Q35y4Hrx1RYQTPOu7FnnGTdVvKdgXzwV7XuGnLs6cSHO16l+bVhI8RoHFcP3SCEoNwyyhVK5jBQJBAPimaKzzZwxnwdwI/T5IR+jd9gzeFg8HGcNnHZlFwHkg13fRtViGX0GYYzwlHX3ZWFn53qWBhajaogFU3btVC4sCQQDJvrB6fMo8NrggzfTCS+u1QxUCtowfUu8K+7qQFJDcKhSDBusBhPTJgwBp+jKkRWClbknO6ZZ6voJ/cu8Q4QhPAkEAokGFIQccgZ3bhUhgaRolwrHE9BSgdGH/z+EkEXbQ6LojoM659fCJjHZymzblDdCctOo2/e2NWOiCuze0EaCnjQJAUE0spbSiMtF8/OG9uNDLY3zuEgRjRdyW9YI5QjxNZLUDMRxB0nr/jG4ubgB+w9Axped+TXPAx96oxt4Stl88FQJAAzNGcVaIW47xocL6wm/ro4/ERTtldQZfpA6OiocOMsNmiakTVyD5qXeK9MyUPsQwojf1uyN0s4s1G+7Zd4z02w==";
    //    static readonly string fzf_pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVzXvqNOtU+PQ7HmkugsHBNKTUj5Ik59kb2YAH4lJWNgyxA1Ef3f3N0SG/q5olFH+Jdtzc/Dx8Po1YlYLTQa8xxJfQhq73t+1sK9tgWCh7COZwdF6wOzz3yRS1H7KiJXL7YIKnbgnwk2zQjs6KlCbrJrqeN99sNxcu9HuyhuHzIQIDAQAB";
    //    static readonly string fzf_api = "http://api.fujinfu.cn:8088/aliwxpay/api/getway";
        
    //    /// <summary>
    //    /// 支付通道回调接口
    //    /// </summary>
    //    /// <returns></returns>
    //    [HttpPost]
    //    public void PayEnd()
    //    {
    //        string inStr = WebHelper.ReadToStr(Request);
    //        //string inStr= "fzfContent={\"version\":\"1.0\",\"random\":\"2019022715021712563414\",\"source\":\"ANDROID\",\"openid\":\"17120000573495\",\"servicecode\":\"notify\",\"key\":\"cVkIHZaWROtdyzxqoj6GFqs9Em5TP0X1YSMyWCsd9iBRTH//Yvr4WnXDrFZDoT9lOFAKhR7r0QBL3HD8nyLbgA7CEKl%2BkxQXqOSoZFfxekRBzIgTEg5cUAxKKy/zF6RWAKtg%2BBVM6I1ElprcXmqRh4OKS3dG5z%2BzU4FGxrdbJnQ=\",\"sign\":\"QMBBMiVkJ%2BjP1QxgoS3fdfJ/oP4lnEurJYMGZHPuhBmqyRngGQiuVTpYesZ9elUHrYtp8G2jjRdzqBqJfwMJFQXW9jQnnLDgA1tMwZWZuuWKWhp84oXx6wJ25emWcO5q5U%2BKChk7k%2BDqSkvo/mYcYAcYkfop74orhp%2BdWk1Z0eg=\",\"data\":\"zGovrDf2ChthAKmB84ta2QmeIZCuDlenHLdxzB4YOK1D0OjT1avei3lvtny5U67HeC3Ro4ezdfLNfZlf1bT/5g2eCiJ3zOzup%2Br1TAL4YoIK1uK8k40K6bGNCzX9otRJ698hBi6dHJVZWja3U6RA7QL/VT8xLSxfHX01KpaclrkQVlgvDjai/Tzg4AlJYBpwq5mh01HImiIefXvf8zOzH6DuhKrz3XIsQqNfNid1yTa7Bsmqw%2BTqWw==\"}";
    //        try
    //        {
    //            //提取DES加密密钥
    //            int keySIdx = inStr.IndexOf("\"key\":\"") + 7;
    //            int keyEIdx = inStr.IndexOf("\",\"sign\":");
    //            string keyRaw = inStr.Substring(keySIdx, keyEIdx - keySIdx).Replace("%2B", "+");
    //            string key = rsaDecrypt2(keyRaw, fq_pvtKey_net);

    //            //使用DES密钥解密业务数据内容
    //            int dataSIdx = inStr.IndexOf("\"data\":\"") + 8;
    //            int dataEIdx = inStr.Length - 2;
    //            string dataRaw = inStr.Substring(dataSIdx, dataEIdx - dataSIdx).Replace("%2B", "+");
    //            string data = desDecrypt(dataRaw, key);

    //            var rtnObj = JObject.Parse(data);
    //            var s = rtnObj.GetValue("orderstatus");
    //            if (s != null && s.Value<string>()== "1")
    //            {
    //                //支付成功
    //                var ordId = rtnObj.GetValue("orderid").Value<string>().TryLong(-1);
    //                string fzfordId = rtnObj.GetValue("fzforderid").Value<string>();
    //                var payTime = rtnObj.GetValue("payendtime").Value<string>().TryDatetime(DateTime.Now);
    //                var payAmount = rtnObj.GetValue("orderamount").Value<string>().TryDecimal(0.0m);
    //                FlashQController.PayEnd(ordId,fzfordId,payAmount,payTime);
    //            }
    //            else
    //            {
    //                //支付失败
    //            }
    //        }
    //        catch
    //        {
    //            //TODO:数据解析失败
    //        }
    //    }

    //    [HttpPost]
    //    public JsonResult PayTest()
    //    {
    //        return Json(Pay("ANDROID", "D", IdFactory.NewID(), 0.01M, "闪Q空间Demo-钱包充值"));
    //    }

    //    /// <summary>
    //    /// 通过富之富平台发起支付
    //    /// </summary>
    //    /// <param name="payType"></param>
    //    /// <param name="paybill"></param>
    //    /// <param name="amount"></param>
    //    public static string Pay(string osType, string payType, long paybill, decimal amount, string remark)
    //    {
    //        DyObject pData = new DyObject();
    //        pData.Set("paytype", payType)
    //            .Set("orderid", paybill.ToString())
    //            .Set("orderamount", amount.ToString())
    //            .Set("ordertime", DateTime.Now.ToString())
    //            .Set("remark", remark)
    //            //.Set("returnurl", "http://sobiz.51vip.biz/fzfpay/payend")
    //            .Set("notifyurl", "http://sobiz.51vip.biz/fzfpay/payend");

    //        Random random = new Random();
    //        string randomStr = DateTime.Now.ToString("MMddHHmmssfff") + random.Next(100, 999);

    //        string signRaw = string.Format("openid={0}random={1}servicecode={2}source={3}version={4}", openid, randomStr, "unifiedorder", osType, "1.0");

    //        //生成一个随机的DES密码用于数据加密，并使用支付平台公钥加密后传递
    //        string key = randomDesKey(8);

    //        //将业务数据先转换为JSON格式
    //        string pDataStr = pData.FastJson();

    //        DyObject pArgs = new DyObject();
    //        signRaw = signRaw.MD5Encrypt_normal().Replace("-", "").ToLower();
    //        pArgs.Set("version", "1.0")
    //             .Set("random", randomStr)
    //             .Set("source", osType)
    //             .Set("openid", openid)
    //             .Set("servicecode", "unifiedorder")
    //             .Set("key", rsaEncrypt2(key, fzf_pubKey_net))   //使用支付平台公钥加密DES密钥
    //             .Set("sign", rsaSign(signRaw, fq_pvtKey))    //使用私钥进行RSA加签
    //             .Set("data", desEncrypt(pDataStr, key));  //使用DES密钥加密业务数据（逻辑参数）

    //        var rtn = WebHelper.PostDataTo(fzf_api, "fzfContent=" + pArgs.FastJson().Replace("+", "%2B"), new DyObject().Set("Content-Type", "application/x-www-form-urlencoded"));

    //        //前端根据返回的数据在手机上拉起微信或支付宝
    //        if (payType == "D")
    //        {
    //            int sIdx = rtn.IndexOf(":\"http") + 2;
    //            int eIdx = rtn.LastIndexOf("\"}}");
    //            string toAli = rtn.Substring(sIdx, eIdx - sIdx);
    //            return toAli;
    //        }
    //        else if (payType == "E")
    //        {
    //            int sIdx = rtn.IndexOf(":\"http")+2;
    //            int eIdx = rtn.LastIndexOf("\"}}");
    //            string toWx = rtn.Substring(sIdx, eIdx - sIdx);
    //            return toWx;
    //        }
    //        else
    //        {
    //            return "";
    //        }
    //    }

    //    public static string randomDesKey(int length)
    //    {
    //        string text = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.,<>/?";
    //        Random random = new Random();
    //        StringBuilder stringBuilder = new StringBuilder();
    //        for (int i = 0; i < length; i++)
    //        {
    //            int startIndex = random.Next(length);
    //            stringBuilder.Append(text.Substring(startIndex, 1));
    //        }
    //        return stringBuilder.ToString();
    //    }

    //    public static string desEncrypt(string src,string key)
    //    {
    //        byte[] rgbKey = Encoding.UTF8.GetBytes(key);
    //        IBlockCipher engine = new DesEngine();
    //        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine),new Pkcs7Padding());
            
    //        cipher.Init(true, new ParametersWithIV(new DesParameters(rgbKey), rgbKey));

    //        byte[] inData = Encoding.UTF8.GetBytes(src);

    //        byte[] rv = new byte[cipher.GetOutputSize(inData.Length)];
    //        int outSize= cipher.ProcessBytes(inData,rv,0);
    //        cipher.DoFinal(rv,outSize);
    //        return Convert.ToBase64String(rv);
    //    }

    //    public static string desDecrypt(string src,string key)
    //    {
    //        byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
    //        IBlockCipher engine = new DesEngine();
    //        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding());
    //        cipher.Init(false, new ParametersWithIV(new DesParameters(rgbKey), rgbKey));

    //        byte[] inData = Convert.FromBase64String(src);
    //        byte[] rv = new byte[cipher.GetOutputSize(inData.Length)];
    //        int outSize= cipher.ProcessBytes(inData,rv,0);
    //        cipher.DoFinal(rv, outSize);
    //        return Encoding.UTF8.GetString(rv);
    //    }

    //    public static string rsaEncrypt(string src,string pubKey)
    //    {
    //        //非对称加密算法，加解密用  
    //        IAsymmetricBlockCipher engine = new RsaEngine();

    //        //加密  
    //        try
    //        {
    //            byte[] pubKeyData = Convert.FromBase64String(pubKey);
    //            //Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubKeyData);
    //            AsymmetricKeyParameter rsaKey = PublicKeyFactory.CreateKey(pubKeyData);

    //            engine.Init(true,rsaKey);
    //            byte[] inData = Encoding.UTF8.GetBytes(src);
    //            var outData = engine.ProcessBlock(inData, 0, inData.Length);
                
    //            return Convert.ToBase64String(outData);
    //        }
    //        catch (Exception ex)
    //        {
    //            return ex.Message;
    //        }
    //    }

    //    public static string rsaEncrypt2(string src, string pubKey)
    //    {
    //        byte[] inData = Encoding.UTF8.GetBytes(src);

    //        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    //        rsa.XFromXmlString(pubKey);

    //        SHA1 halg = new SHA1CryptoServiceProvider();
    //        byte[] inArray = rsa.Encrypt(inData,false);
    //        return Convert.ToBase64String(inArray);
    //    }

    //    public static string rsaDecrypt(string src,string pvtKey)
    //    {
    //        //非对称加密算法，加解密用  
    //        IAsymmetricBlockCipher engine = new RsaEngine();

    //        //解密  
    //        try
    //        {
    //            byte[] pvtKeyData = Convert.FromBase64String(pvtKey);
    //            Asn1Object pvtKeyObj = Asn1Object.FromByteArray(pvtKeyData);
    //            AsymmetricKeyParameter rsaKey = PrivateKeyFactory.CreateKey(pvtKeyData);

    //            engine.Init(false, rsaKey);
    //            byte[] inData = Convert.FromBase64String(src);
    //            var outData = engine.ProcessBlock(inData, 0, inData.Length);
                
    //            return Encoding.UTF8.GetString(outData);
    //        }
    //        catch (Exception ex)
    //        {
    //            return ex.Message;
    //        }
    //    }

    //    public static string rsaDecrypt2(string src, string pvtKey_net)
    //    {
    //        byte[] inData = Convert.FromBase64String(src);
    //        //解密  
    //        try
    //        {
    //            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    //            rsa.XFromXmlString(pvtKey_net);
    //            SHA1 halg = new SHA1CryptoServiceProvider();
    //            byte[] outData = rsa.Decrypt(inData, false);
    //            return Encoding.UTF8.GetString(outData);
    //        }
    //        catch (Exception ex)
    //        {
    //            return ex.Message;
    //        }
    //    }

    //    public static string rsaSign(string src,string pvtKey)
    //    {
    //        //非对称加密算法，加解密用  
    //        var signer = SignerUtilities.GetSigner("SHA1WithRSA");
            
    //        //签名  
    //        try
    //        {
    //            byte[] pvtKeyData = Convert.FromBase64String(pvtKey);
    //            AsymmetricKeyParameter pvtKeyObj = PrivateKeyFactory.CreateKey(pvtKeyData);
    //            signer.Init(true, pvtKeyObj);
                
    //            byte[] inData = Encoding.UTF8.GetBytes(src);
    //            signer.BlockUpdate(inData,0,inData.Length);
    //            return Convert.ToBase64String(signer.GenerateSignature());
    //        }
    //        catch (Exception ex)
    //        {
    //            return ex.Message;
    //        }
    //    }

    //    public static string rsaSign2(string src,string pvtKey)
    //    {
    //        byte[] bytes = Encoding.UTF8.GetBytes(src);

    //        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    //        rsa.XFromXmlString(pvtKey);

    //        SHA1 halg = new SHA1CryptoServiceProvider();
    //        byte[] inArray = rsa.SignData(bytes, halg);
    //        return Convert.ToBase64String(inArray);
    //    }

    //    public static bool rsaVertify(string src,string sign,string pubKey)
    //    {
    //        //非对称加密算法，加解密用  
    //        IAsymmetricBlockCipher engine = new RsaEngine();

    //        //签名验证  
    //        try
    //        {
    //            byte[] pubKeyData = Convert.FromBase64String(pubKey);
    //            Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubKeyData);
    //            AsymmetricKeyParameter rsaKey = PublicKeyFactory.CreateKey(pubKeyData);

    //            engine.Init(true, rsaKey);
    //            byte[] inData = Encoding.UTF8.GetBytes(src);
    //            var outData = engine.ProcessBlock(inData, 0, inData.Length);
    //            return String.Equals(Convert.ToBase64String(outData), sign);
    //        }
    //        catch (Exception ex)
    //        {
    //            return false;
    //        }
    //    }
    //}

    public static class HexToASCI
    {
        public static string ConvertStr(string hexStr) {       
            string[] inStr = hexStr.Split(' ');
            byte[] buff = new byte[inStr.Length];
            for (int i = 0; i < inStr.Length; i += 1) {
                buff[i] =Convert.ToByte(inStr[i], 16);
            }
            string result = Encoding.ASCII.GetString(buff);
            return result;
        }
    }
}